/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package work.hutool.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import work.entity.Student;
import work.entity.User;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Sakura Shen
 * @description JSON工具
 * @date 2021/8/20
 */
public class JsonUtilTest02 {


    public static void main(String[] args) {

        // 1. JSONObject对应的JSON字符串
        String jsonStr = "{\"name\":\"张三\",\"sex\":\"男\"}";
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);

        // 2. 直接把JSON字符串转成JSONObject
        JSONObject jsonObject1 = new JSONObject(jsonStr);


        // 3. JSONArray对应的JSON字符串
        String jsons1 = "[{\"id\":\"01\",\"open\":false,\"pId\":\"0\",\"name\":\"A部门\"},{\"id\":\"01\",\"open\":false,\"pId\":\"0\",\"name\":\"A部门\"},{\"id\":\"011\",\"open\":false,\"pId\":\"01\",\"name\":\"A部门\"},{\"id\":\"03\",\"open\":false,\"pId\":\"0\",\"name\":\"A部门\"},{\"id\":\"04\",\"open\":false,\"pId\":\"0\",\"name\":\"A部门\"}, {\"id\":\"05\",\"open\":false,\"pId\":\"0\",\"name\":\"A部门\"}, {\"id\":\"06\",\"open\":false,\"pId\":\"0\",\"name\":\"A部门\"}]";
        JSONArray jsonArray = JSONUtil.parseArray(jsons1);
        System.out.println(jsonArray);


        // 4. JSONObject 转 bean
        String s1 = "{\"name\":\"张三\",\"age\":\"15\"}";
        JSONObject stuJsonObj = JSONUtil.parseObj(s1);
        Student student = stuJsonObj.toBean(Student.class);
        System.out.println(student);

        // 5. map转Json
        Map<String,String> map = new HashMap<>();
        map.put("a","1");
        map.put("b","2");
        map.put("c","3");
        JSONObject j1 = JSONUtil.parseObj(map);

        // json转map 暂时没有

        // 6. json转xml字符串
        String xmlString  = JSONUtil.toXmlStr(j1);

        // 7 JSONUtil.toJsonStr() 把JavaBean对象转化为JSON字符串 字段值为null会自动忽略掉
        User user = new User();
        user.setId("123");
        user.setName("SML");
        String userStr = JSONUtil.toJsonStr(user);
        String aa = JSONUtil.toJsonStr(null);

        System.out.println("END");

    }

}
